package ext.mango.ab.so;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import mango.functions.FuncDate;
import mango.orm.DaoFactory;
import mango.orm.DBSession;
import mango.orm.DBSessionFactory;
import mango.service.Service;
import mango.web.Info;
import ext.mango.ab.eo.EOABHouseKeeper2;
import ext.mango.ab.eo.EOABHouseKeeperDetail;
import ext.mango.ab.eo.EOABHouseKeeperSpendType;
import ext.mango.ab.po.HouseKeeper2;
import ext.mango.base.SOBase;
import ext.mango.functions.Func;

@Service
public class SOABHouseKeeper2 extends SOBase {
    
    public EOABHouseKeeperSpendType getSpendTypeName(String spendItem, String userId){
//        String sql = "select * from BaseCode where codetype='spendtype' and code = nvl((select spendtype from ABHouseKeeperTypeItems where item=? and rownum=1), 'default')";
        String sql = "select * from ABHouseKeeperSpendType where (operator=? or operator='default') and spendtype = ifnull((select spendtype from ABHouseKeeperTypeItems where item=? and operator=? limit 0, 1), 'default')";
        EOABHouseKeeperSpendType ret = (EOABHouseKeeperSpendType) DaoFactory.c(sql, EOABHouseKeeperSpendType.class).setParameter(userId, spendItem, userId).uniqueResult();
        return ret;
    }
    
    public void createHouseKeeper(HouseKeeper2 action) {
        String olditems = action.getRequestParameter("ITEMS");
        Date actionDate = action.getRequestDate("ACTIONDATE");
        Date mkdate = new Date();
        String mktime = FuncDate.getCurrentTime();
        EOABHouseKeeper2 keeper2 = new EOABHouseKeeper2();
        String keepid = Func.getSequenceNo("KEEP");
        keeper2.setID(keepid)
            .setItems(olditems)
            .setActionDate(actionDate)
            .setOperator(action.getCurrentUser().getId())
            .setMakeDate(mkdate)
            .setMakeTime(mktime)
            .setModifyDate(mkdate)
            .setModifyTime(mktime);
        DBSession session = DBSessionFactory.getSession();
        session.save(keeper2);
        session.save(this.getDetails(olditems, actionDate, keepid, mkdate, mktime, action.getCurrentUser().getId()));
        session.commit();
        action.addInfo(Info.SUCCESS, keepid);
    }
    
    public void updateHouseKeeper(HouseKeeper2 action) {
        String olditems = action.getRequestParameter("ITEMS");
        Date actionDate = action.getRequestDate("ACTIONDATE");
        String queryId = action.getRequestParameter("QUERYID");
        Date mkdate = new Date();
        String mktime = FuncDate.getCurrentTime();
        EOABHouseKeeper2 keeper2 = new EOABHouseKeeper2();
        keeper2.setEntity(keeper2.setID(queryId).unique());
        keeper2.setModifyDate(mkdate).setModifyTime(mktime).setActionDate(actionDate).setItems(olditems);
        DBSession session = DBSessionFactory.getSession();
        session.update(keeper2);
        session.execute("delete from ABHouseKeeperDetail where pid=?", queryId);
        session.save(this.getDetails(olditems, actionDate, queryId, mkdate, mktime, action.getCurrentUser().getId()));
        session.commit();
        action.addInfo(Info.SUCCESS, queryId);
    }
    
    public List<EOABHouseKeeperDetail> getDetails(String olditems, Date actionDate, String keepid, Date mkdate, String mktime, String userId){
        String items = olditems.replaceAll(",|，|。|;|；|、|：|:|/|\\|", "");
        items = items.replaceAll("\\p{Blank}*", "");
        String regex = "\\d*\\.*\\d";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(items);
        List<EOABHouseKeeperDetail> details = new ArrayList<EOABHouseKeeperDetail>();
        String tmp = items;
        while(matcher.find()){
            String money = matcher.group();
            int idx = tmp.indexOf(money);
            String item = tmp.substring(0, idx);
            logger.debug(tmp + " : " + item + " : " + money);
            tmp = tmp.substring(idx + money.length());
            EOABHouseKeeperSpendType code = this.getSpendTypeName(item, userId);
            EOABHouseKeeperDetail detail = new EOABHouseKeeperDetail();
            detail.setPID(keepid)
                  .setActionDate(actionDate)
                  .setSpendType(code.getSpendType())
                  .setSpendName(code.getName())
                  .setMakeDate(mkdate)
                  .setMakeTime(mktime)
                  .setMoney(Double.parseDouble(money))
                  .setSubSpendName(item)
                  .setActionMonth(FuncDate.getMonth(actionDate))
                  .setOperator(userId)
                  .setID(Func.getSequenceNo("ITEM"));
            details.add(detail);
        }
        return details;
    }
}